<?php

namespace app\api\controller\kuyou\applet;

use app\common\model\Attachment;
use app\api\model\kuyou\applet\Suppliers as Supplierss;
use app\api\model\kuyou\applet\Sets;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date as PHPExcel_Shared_Date;
/**
 * 供应商接口
 */
class Suppliers extends Common
{
    protected $noNeedRight = ['getDetail'];

    /**
     * 获取供应商
     * @ApiMethod (POST)
     * @param int $page 页码
     * @param int $limit 每页条数
     * @param string $name 供应商名称
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->post('page');
            $page = empty($page)?1:$page;
            $limit = $this->request->post('limit');
            $limit = empty($limit)?config('app_limit'):$limit;

            $where = [];
            $keyword = $this->request->post('keyword');
            if(!empty($keyword)){
                $where['supplyer_name|supplyer_code'] = ['like','%'.$keyword.'%'];
            }else{
                $code = $this->request->post('supplyer_code');
                if(!empty($code)){
                    $where['supplyer_code'] = ['like','%'.$code.'%'];
                }
                $name = $this->request->post('supplyer_name');
                if(!empty($name)){
                    $where['supplyer_name'] = ['like','%'.$name.'%'];
                }
            }
            $supplyertype_id = $this->request->post('supplyertype_id');
            if(!empty($supplyertype_id)){
                $where['supplyertype_id'] = $supplyertype_id;
            }
            $status = $this->request->post('status');
            if ($status==-1){
                $where['status'] = 0;
            }else if(!empty($status)){
                $where['status'] = $status;
            }

            $result = Supplierss::getList($where,$page,$limit);

            if(isset($result['list']) && isset($result['count'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取供应商详情
     * @ApiMethod (POST)
     * @param int $id 供应商ID
     */
    public function getdetail()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            if(empty($id)){
                $this->error('请输入查询参数','',500);
            }
            $result = Supplierss::getDetail($id);
            if($result['status']==200){
                $this->success('查询成功',$result['msg'],200);
            }else{
                $this->error($result['msg'],'',$result['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 添加供应商
     * @ApiMethod (POST)
     * @param array $detail 供应商数据
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $ret = Supplierss::addDetail($data);
            if($ret['status']==200){
                $this->success('添加成功',$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 更新供应商
     * @ApiMethod (POST)
     * @param array $detail 供应商数据
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $ret = Supplierss::editDetail($data);
            if($ret['status']==200){
                $this->success('更新成功','',200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 删除供应商
     * @ApiMethod (POST)
     * @param int $id 供应商id
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $ret = Supplierss::delDetail($id);
            if($ret['status']==200){
                $this->success('删除成功',$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 导入供应商
     * @ApiMethod (POST)
     * @param string $file 供应商文件路径（先上传文件后直接传入文件路径）
     */
    public function import()
    {
        if ($this->request->isPost()) {
            $file = $this->request->post('file');
            $type = $this->request->post('type');
            if(empty($file)){
                $this->error('请选择上传文件','',500);
            }

            $set_time = (new Sets())::getSet('enable_time');
            $set_time = isset($set_time[0]['value'])?strtotime($set_time[0]['value']):time();

            $filePath = ROOT_PATH . 'public' . $file;
            $filePath = str_replace("\\",'/',$filePath);
            if (!is_file($filePath)) {
                $this->error('未找到上传文件，请重新上传','',500);
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error('文件格式错误，请重新上传','',500);
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);
                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error('读取文件失败，请重新上传','',500);
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $val = str_replace('*','',$val);
                        $fields[] = (string)$val;
                    }
                }
                if(!in_array('供应商编号',$fields) || !in_array('供应商名称',$fields)){
                    exception('数据格式错误，请重新上传');
                }

                for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = array_combine($fields, $values);
                    if( !empty($row['余额日期'])){
                        $row['余额日期'] =  strtotime(gmdate('Y-m-d H:i:s',PHPExcel_Shared_Date::excelToTimeStamp($row['余额日期'])));
                    }else{
                        $row['余额日期'] =  $set_time;
                    }
                    $insert[] = $row;
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage(),'',500);
            }
            if (!$insert) {
                $this->error('未读取到有效数据，请重新上传','',500);
            }
            $params = [];
            $code = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['供应商编号']) && !empty($insert_v['供应商名称'])){
                    if(!in_array($insert_v['供应商编号'],$code)){
                        $code[] = $insert_v['供应商编号'];
                    }else{
                        $this->error('导入失败，编号'.$insert_v['供应商编号'].'重复','',500);
                    }
                    $status = checkCode($insert_v['供应商编号'],2);//验证编号是否合法
                    if(!$status){
                        $this->error('导入失败，编号'.$insert_v['供应商编号'].'不合法','',500);
                    }
                }
            }

            $cate = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(empty($insert_v['供应商编号']) || empty($insert_v['供应商名称']) || empty($insert_v['联系人'])){
                    unset($insert[$insert_k]);
                }else{
                    if(!empty($insert_v['供应商类别']) && !in_array($insert_v['供应商类别'],$cate)){
                        $cate[] = $insert_v['供应商类别'];
                    }
                }
            }

            $catelist = (new \app\common\model\Supplyertype())->where(['supplier_type_name'=>['in',$cate]])->column('id','supplier_type_name');
            $catename = (new \app\common\model\Supplyertype())->where(['supplier_type_name'=>['in',$cate]])->column('supplier_type_name');
            if(sizeof($catename)!=sizeof($cate)){
                foreach ($cate as $cate_k=>$cate_v){
                    if(!in_array($cate_v,$catename)){
                        $this->error('供应商分类'.$cate_v.'不存在，导入失败');
                    }
                }
            }

            $params = [];
            $nowsp = '';
            $supplyer_code = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['供应商编号']) && !empty($insert_v['供应商名称'])){
                    $nowsp = $insert_k;
                    if(in_array($insert_v['供应商编号'],$supplyer_code)){
                        $this->error('导入失败，供应商编号'.$insert_v['供应商编号'].'重复');
                    }
                    $supplyer_code[] = $insert_v['供应商编号'];
                    $params[$insert_k] = [
                        'supplyer_code'     => $insert_v['供应商编号'],
                        'supplyer_name'     => $insert_v['供应商名称'],
                        'supplyertype_id'   => isset($catelist[$insert_v['供应商类别']])?$catelist[$insert_v['供应商类别']]:0,
                        'account_time'      => !empty($insert_v['余额日期'])?$insert_v['余额日期']:time(),
                        'opening_payable'   => $insert_v['期初应付款'],
                        'opening_prepayment'=> $insert_v['期初预付款'],
                        'need_give_account' => round(((float)$insert_v['期初应付款']-(float)$insert_v['期初预付款']),2),
                        'vat_rate'          => $insert_v['增值税税率'],
                        'identification'    => $insert_v['纳税人识别号'],
                        'deposit_bank'      => $insert_v['开户银行'],
                        'bank_number'       => $insert_v['银行账号'],
                        'note'              => $insert_v['备注'],

                        'first_connect_name'=> $insert_v['联系人'],
                        'first_connect_mobile'=> $insert_v['手机'],
                        'first_connect_phone'=> $insert_v['座机'],
                        'qq_wx_email'       => $insert_v['QQ/微信/Email'],
                        'connect_address'   => $insert_v['联系地址'],
                        'userlist'          =>[]
                    ];
                }

                if(isset($params[$nowsp]['userlist'])){
                    $params[$nowsp]['userlist'][] = [
                        'supplyer_code'         => $params[$nowsp]['supplyer_code'],
                        'first_connect_name'    => $insert_v['联系人'],
                        'first_connect_mobile'  => $insert_v['手机'],
                        'first_connect_phone'   => $insert_v['座机'],
                        'qq_wx_email'           => $insert_v['QQ/微信/Email'],
                        'connect_address'       => $insert_v['联系地址'],
                        'is_first'              => ($nowsp==$insert_k)?1:0,
                    ];
                }
            }

            $editstatus = isset($_POST['editstatus'])?$_POST['editstatus']:1;
            $edit_arr = [];
            if($editstatus==0){
                (new \app\common\model\Suppliers)->where(['supplyer_code'=>['in',$supplyer_code]])->value('supplyer_code');
                if(!empty($code)){
                    $this->error('导入失败，供应商编号'.$code.'已存在');
                }
            }else{
                $code_list = (new \app\common\model\Suppliers)->where(['supplyer_code'=>['in',$supplyer_code]])->column('id','supplyer_code');
                foreach ($params as $params_k=>$params_v){
                    if(isset($code_list[$params_v['supplyer_code']])){
                        $params_v['id'] = $code_list[$params_v['supplyer_code']];
                        $edit_arr[] = $params_v;
                        unset($params[$params_k]);
                    }
                }
            }

            $ret = Supplierss::import($params,$edit_arr);
            if($ret['status']==200){

                //导入成功删除文件
                $file = $this->request->post('file');
                $attachment = (new Attachment())->where(['url'=>$file])->find();
                if($attachment){
                    \think\Hook::add('upload_delete', function ($attachment) {
                        if ($attachment['storage'] == 'local') {
                            $attachmentFile = ROOT_PATH . '/public' . $attachment['url'];
                            if (is_file($attachmentFile)) {
                                @unlink($attachmentFile);
                            }
                        }
                    });
                    \think\Hook::listen("upload_delete", $attachment);
                    (new Attachment())->where(['url'=>$file])->delete();
                }

                $this->success('导入成功','',200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }
}
